package com.ccl.iot.device;

import android.util.Log;

import com.ccl.iot.IOTDataType;
import com.ccl.iot.IOTNetAPI;
import com.ccl.iot.R;
import com.ccl.iot.dvr.utils.LoggerUtil;
import com.ccl.iot.managers.DeviceManager;
import com.ccl.iot.object.IOTDeviceInfoEx;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.updater.HttpHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class IOTMultiFunc5525 extends IOTComplexDevice {

    private static final int UUID_ADDRESS = 8; // UUID的地址
    private static final int UUID_SIZE = 4; // UUID的大小
    private static final int VERSION_ADDRESS = UUID_ADDRESS + UUID_SIZE; // 版本的地址
    private static final int VERSION_SIZE = 4; // 版本的大小
    private static final int PATCH_ADDRESS = VERSION_ADDRESS + VERSION_SIZE; // 补丁的地址

    private int mBaseReg = 8;
    private int mCurrentUUID = 0;
    private DeviceManager mDeviceManager;
    private boolean isInit = true;
    private Map<String, String> mPatchDes;
    private boolean mUpgradePatch = false;

    public IOTMultiFunc5525(long aDevID, IOTDeviceInfoEx aDeviceInfo, int aStateAddress, int aStateSize) {
        super(aDevID, aDeviceInfo, aStateAddress, aStateSize);
        mDeviceManager = DeviceManager.GetDefaultManager();
    }

    public boolean hasPatch() {
        return mCurrentUUID != 0 && iDevices != null;
    }

    @Override
    public void updateRegister(int aAddress, int aSize, byte[] aData, int aDataPos, int aNetWork, long time) {
        // super.updateRegister(aAddress, aSize, aData, aDataPos, aNetWork, time);
        saveRegister(aAddress, aSize, aData, aNetWork);
        // 如果有修改UUID则更换控制设备
        if ((aAddress == UUID_ADDRESS || aAddress == 0) && aData != null) {
            int pos = 0;
            if (aAddress == 0) {
                pos += UUID_ADDRESS;
            }
            int uuid = IOTDataType.C32(aData, pos);
            processUUID(uuid);
        }
        if (iDevices != null && iDevices.length > 0) {
            if (aAddress < PATCH_ADDRESS) {
                int point = PATCH_ADDRESS + mBaseReg;
                for (IOTDevice dev : iDevices) {
                    int offset = point - aAddress;

                    byte[] newData = new byte[dev.getRegisterSize()];
                    for (int i = 0; i < newData.length; i++) {
                        newData[i] = aData[offset++];
                    }
                    point += newData.length;

                    dev.updateRegister(dev.getRegisterAddress(), newData.length, newData, 0, aNetWork, time);

                }
            } else {
                int startReg;
                int endReg;
                for (IOTDevice dev : iDevices) {
                    startReg = dev.getRegisterAddress();
                    endReg = dev.getRegisterSize() + startReg;
                    if (aAddress >= startReg && aAddress < endReg) {
                        dev.updateRegister(aAddress, aSize, aData, aDataPos, aNetWork, time);
                        break;
                    }
                }
            }

//            if (isInit) {
//                mDeviceManager.startScan(null);
//                isInit = false;
//            }
        }
    }

    private void processUUID(int uuid) {
        if (mCurrentUUID != uuid) {
            mPatchDes = null;
            if (mDeviceManager != null) {
                LoggerUtil.i("uuid", "uuid---" + String.format("%02X", uuid));
                mBaseReg = 8;
                switch (uuid) {
                    case IOTDeviceConst.PATCH_UUID.EPATCH_UUID_AC_DAIKIN_VRV_8CH: // 8路空调
//                        mDeviceManager.removeDevice(getID());
                        IOTDevice air8Dev = mDeviceManager.addDevice(-getID(), new IOTDeviceInfoEx(IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_AIR_CONDITION_8,
                                getDeviceInfo().iModel, getDeviceInfo().iVersion, IOTDeviceConst.TDEVREG_SIZE.EDEVREG_TERMINAL_AIRCONDITION_SIZE_8));
                        if (air8Dev != null) {
                            air8Dev.setOnline(true);
                            //                            mDeviceManager.addOnlineDev(air8Dev);
                            if (air8Dev instanceof IOTComplexDevice) {
                                iDevices = ((IOTComplexDevice) air8Dev).getDevices();
                                if (iDevices != null) {
                                    for (IOTDevice dev : iDevices) {
                                        dev.setAuthState(getNetWorkState(), getAuth());
                                    }
                                }
                            }
                        }
                        break;
                    case IOTDeviceConst.PATCH_UUID.EPATCH_UUID_AT_RF_PROBE_16CH: // 探头
                        mDeviceManager.removeDevice(getID());
                        IOTDevice probeDev = mDeviceManager.addDevice(getID(), new IOTDeviceInfoEx(IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_ANTI_THEFT_PROBE,
                                getDeviceInfo().iModel, getDeviceInfo().iVersion, IOTDeviceConst.TDEVREG_SIZE.EDEVREG_TERMINAL_PROBE_SIZE * 16));
                        if (probeDev != null) {
                            probeDev.setOnline(true);
                            mDeviceManager.addOnlineDev(probeDev);
                            probeDev.setAuthState(getNetWorkState(), getAuth());
                            iDevices = new IOTDevice[]{probeDev};
                        }

                        break;
                    case IOTDeviceConst.PATCH_UUID.EPATCH_UUID_SECURITY_ARM_32CH: // 安防探头
                        mDeviceManager.removeDevice(getID());
                        IOTDevice securityArmDev = mDeviceManager.addDevice(getID(), new IOTDeviceInfoEx(IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_SECURITY_ARM,
                                getDeviceInfo().iModel, getDeviceInfo().iVersion, IOTDeviceConst.TDEVREG_SIZE.EDEVREG_TERMINAL_SECURITYARM_SIZE));
                        if (securityArmDev != null) {
                            securityArmDev.setOnline(true);
                            mDeviceManager.addOnlineDev(securityArmDev);
                            securityArmDev.setAuthState(getNetWorkState(), getAuth());
                            iDevices = new IOTDevice[]{securityArmDev};
                        }
                        break;
                    case IOTDeviceConst.PATCH_UUID.EPATCH_UUID_AC_DAIKIN_VRV_25CH: // 25路空调
                        Log.e("Air25", "25-------------");
                        mBaseReg = 10;
//                        mDeviceManager.removeDevice(getID());
                        IOTDevice air25Dev = mDeviceManager.addDevice(-getID(), new IOTDeviceInfoEx(IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_AIR_CONDITION_25,
                                getDeviceInfo().iModel, getDeviceInfo().iVersion, IOTDeviceConst.TDEVREG_SIZE.EDEVREG_TERMINAL_AIRCONDITION_SIZE_25));
                        if (air25Dev != null) {
                            air25Dev.setOnline(true);
                            //                            mDeviceManager.addOnlineDev(air25Dev);
                            if (air25Dev instanceof IOTComplexDevice) {
                                iDevices = ((IOTComplexDevice) air25Dev).getDevices();
                                if (iDevices != null) {
                                    for (IOTDevice dev : iDevices) {
                                        dev.setAuthState(getNetWorkState(), getAuth());
                                    }
                                }
                            }
                        }
                        break;
                    default: // 无补丁
                        iDevices = null;
                        break;
                }
            }
            isInit = true;
            mCurrentUUID = uuid;
//            mDeviceManager.startScan(null);

            if (mCurrentUUID != 0 && isOwner()) {
                ThreadPoolUtils.getInstance().addTask(new Runnable() {

                    @Override
                    public void run() {
                        //						http://iot.cclcp.com:5499/Downloads/Patch/[UUID：如73010008]/patch.bin
                        String desPath = "http://iot.cclcp.com:5499/Downloads/Patch/" + Integer.toHexString(mCurrentUUID) + "/patch.json";
                        String json = HttpHelper.GetHttpRequestString(desPath);
                        Log.e("PROBE", "Json: " + json);
                        if (json != null) {
                            mPatchDes = new HashMap<String, String>();
                            int code = 0;
                            String version = null;
                            String date = null;
                            long fileSize = 0;
                            String forceUpdateVersion = null;
                            String description = null;
                            try {
                                JSONObject parser = new JSONObject(json);
                                code = parser.getInt("Code");
                                version = parser.getString("Version");
                                date = parser.getString("Date");
                                fileSize = parser.getLong("FileSize");
                                forceUpdateVersion = parser.getString("ForceUpdateVersion");
                                description = parser.getString("Description");

                                mPatchDes.put("Code", code + "");
                                mPatchDes.put("Version", version);
                                mPatchDes.put("Date", date);
                                mPatchDes.put("FileSize", fileSize + "");
                                mPatchDes.put("ForceUpdateVersion", forceUpdateVersion);
                                mPatchDes.put("Description", description);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            mUpgradePatch = verifyUUID(mCurrentUUID, code);
                        }
                    }
                });
            }
        }
    }

    private boolean verifyUUID(final int uuid, final int version) {
        return IOTNetAPI.GetInstance().patchVerify(getID(), uuid, version);
    }

    public int getUUID() {
        return mCurrentUUID;
    }

    public boolean upgradePatchable() {
        return mUpgradePatch;
    }

    public Map<String, String> getPatchDes() {
        return mPatchDes;
    }

    // ------------super function---------------

    @Override
    public int getDeviceCount() {
        if (!hasPatch()) {
            return 1;
        } else {
            return super.getDeviceCount();
        }
    }

    @Override
    public IOTDevice getDevice(int aIndex) {
        if (!hasPatch() && aIndex == 0) {
            return this;
        } else {
            return super.getDevice(aIndex);
        }
    }

    @Override
    public int getImageId() {
        return R.drawable.icon_unknown;
    }

}
